package com.mingqijia.gassafety.webserver.webSocket;

import com.alibaba.fastjson.JSONObject;
import com.mingqijia.gassafety.db.entity.Organization;
import com.mingqijia.gassafety.webserver.service.OrganizationService;
import com.mingqijia.gassafety.webserver.utils.ApplicationContextUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Author: duanhongxiang
 * @Date: 2024/6/6 17:54
 */
@Component
@Slf4j
public class WebSocketUserMessageListener implements MessageListener {
    private static final String split = ";;";
    
    @Autowired
    OrganizationService organizationService;
    
    @SneakyThrows
    @Override
    public void onMessage(Message message, byte[] bytes) {
        log.info("WebSocketUserMessageListener:监听到redis消息：{}", message);
        byte[] body = message.getBody();
        if (body.length > 0) {
            String mess = new String(message.getBody(), StandardCharsets.UTF_8).trim().replaceAll("\\\\", "");
            if (mess.length() >= 2) mess = mess.substring(1, mess.length() - 1);
            // 发送消息
            String spId = "";
            if (mess.contains(split)) {
                String[] split = mess.split(WebSocketUserMessageListener.split);
                mess = split[0];
                spId = split[1];
            }
            if (organizationService==null){
                organizationService = ApplicationContextUtils.getBean(OrganizationService.class);
            }
            List<Organization> organizations = organizationService.getParentIdBySpid(spId);
            log.info("onMessage-organizations:{}", JSONObject.toJSONString(organizations));

            WebSocketUserProcess.sendMessage(spId, mess, organizations);
        }
    }
}
